#pragma Once
#include <sys/stat.h>
#include <fstream>
#include <regex>
#include <sys/stat.h>
#include "../server.hpp"

std::unordered_map<int, std::string> _status_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

class Util
{
public:
    // 字符串分割
    static size_t Split(const std::string &str, const std::string &seq, std::vector<std::string> *arry)
    {
        int offset = 0;
        while (offset < str.size())
        {
            // abc....bcd.aaa.
            size_t pos = str.find(seq, offset);
            if (pos == std::string::npos) // 如果没找到则表示要截取最后一个字符串
            {
                arry->push_back(str.substr(offset));
                return arry->size();
            }
            // 找到则pos指向【.】的下标
            if (pos == offset) // 代表存在多个【.】，截取的字符没有任何意义
            {
                offset = pos + seq.size();
                continue;
            }
            arry->push_back(str.substr(offset, pos - offset));
            offset = pos + seq.size();
        }
        return arry->size();
    }

    // 读取字符串内容
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false)
        {
            Log::ERROR("open %s false", filename.c_str());
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0, ifs.end); // 跳转到文件末尾
        fsize = ifs.tellg();   // 获取当前读写位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
        ifs.seekg(0, ifs.beg); // 跳转到文件起始位置

        buf->resize(fsize);
        ifs.read(&(*buf)[0], fsize);
        if (ifs.good() == false)
        {
            Log::ERROR("read %s false", filename.c_str());
            ifs.close();
            return false;
        }

        ifs.close();
        return true;
    }

    // 向文件写入数据
    static bool WriteFile(const std::string &filename, const std::string &buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc); // 在打开文件时，把已有内容全部清空（truncate to zero length）
        if (ofs.is_open() == false)
        {
            Log::ERROR("open %s false", filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good() == false)
        {
            Log::ERROR("read %s false", filename.c_str());
            ofs.close();
            return false;
        }

        ofs.close();
        return true;
    }

    // URL 编码
    static std::string UrlEncode(const std::string &url, bool convert_space_to_plus)
    {
        std::string res;
        for (unsigned char c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))
            {
                res += c;
            }
            else if (c == ' ' && convert_space_to_plus)
            {
                res += '+';
            }
            else
            {
                char tmp[4] = {0};
                snprintf(tmp, 4, "%%%02X", c);
                res += tmp;
            }
        }
        return res;
    }

    // %2B == 43
    // 只支持 '0'-'9' 和 'A'-'F'
    static int CtoInt(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;

        // 非法字符直接返回 -1（也可以选择抛异常或忽略）
        return -1;
    }

    // URL 解码
    static std::string UrlDecode(const std::string &url, bool convert_plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '%')
            {
                if (i + 2 < url.size())
                {
                    int c1 = CtoInt(url[i + 1]);
                    int c2 = CtoInt(url[i + 2]);
                    if (c1 != -1 && c2 != -1)
                    {
                        res += static_cast<char>(c1 * 16 + c2);
                        i += 2;
                        continue;
                    }
                }
                // 如果不是有效的 %xx，直接保留 %
                res += '%';
            }
            else if (url[i] == '+' && convert_plus_to_space)
            {
                res += ' ';
            }
            else
                res += url[i];
        }
        return res;
    }

    // 响应状态码的描述信息获取
    static std::string StatusDesc(int status)
    {

        auto it = _status_msg.find(status);
        if (it != _status_msg.end())
        {
            return it->second;
        }
        return "Unknow status";
    }
    // 根据文件后缀名获取文件mine
    static std::string GetMimeTypeFromExtension(const std::string &filename)
    {

        // 获取文件扩展名 a.txt
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string ext = filename.substr(pos);
        // 通过扩展名获取mime
        auto it = _mime_msg.find(ext);
        if (it != _mime_msg.end())
        {
            return it->second;
        }
        return "application/octet-stream";
    }

    // 判断一个文件是否是目录
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是普通文件
    static bool IsRegularFile(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // http请求路径是否有效
    static bool ValidPath(const std::string &path)
    {
        std::vector<std::string> sub;
        Split(path, "/", &sub);
        int level = 0;
        for (auto &s : sub)
        {
            if (s == "..")
            {
                level--;
                if (level < 0)
                    return false;
                continue;
            }

            if (s != ".")
                level++;
        }
        return true;
    }
};

class HttpRequest
{
public:
    std::string _method;                                   // 请求方法
    std::string _path;                                     // 资源路径
    std::string _version;                                  // 协议版本
    std::string _body;                                     // 请求正文
    std::smatch _matches;                                  // 资源路径的正则提取数据
    std::unordered_map<std::string, std::string> _headers; // http头部字段
    std::unordered_map<std::string, std::string> _params;  // 查询字符串
public:
    HttpRequest() : _version("HTTP/1.1") {}
    void ReSet()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch matches;
        _matches.swap(matches);
        _headers.clear();
        _params.clear();
    }
    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    // 判断是否存在指定的头部字段
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定头部字段的值
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    // 插入查询字符串
    void SetParam(const std::string &key, const std::string &val)
    {
        _params.insert(std::make_pair(key, val));
    }
    // 判断是否有指定的查询字符串
    bool HasParam(const std::string &key)
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定的查询字符串
    std::string GetParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return "";
        }
        return it->second;
    }

    // 获取正文长度
    size_t ContentLength() const
    {
        if (HasHeader("Content-Length") == false)
        {
            return 0;
        }
        std::string content = GetHeader("Content-Length");
        return std::stol(content);
    }
    // 判断是否是短连接
    bool Close() const
    {
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            
            return false;
        }

        //Log::DEBUG("长连接");
        return true;
    }
};

class HttpResponse
{
public:
    int _status;                                           // 状态码
    bool _redirect_flag;                                   // 重定向标志
    std::string _redirect_url;                             // 重定向路径
    std::unordered_map<std::string, std::string> _headers; // http头部字段
    std::string _body;                                     // 回复正文
public:
    HttpResponse() : _status(200), _redirect_flag(false) {}
    HttpResponse(int status) : _status(status), _redirect_flag(false) {}

    void ReSet()
    {
        _status = 200;
        _redirect_flag = false;
        _redirect_url.clear();
        _headers.clear();
        _body.clear();
    }

    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &val)
    {
        // std::cout << "插入的键值对是： " << key << ": " << val << std::endl;
        _headers.insert(std::make_pair(key, val));
    }
    // 判断是否存在指定的头部字段
    bool HasHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定头部字段的值
    std::string GetHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    void SetContent(const std::string &body, const std::string &type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }

    void SetRedirect(const std::string &url, int status = 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;
    }

    // 判断是否是短连接
    bool Close()
    {
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }
};

typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatus;

#define MAX_LINE 8192
class HttpContext
{
private:
    int _resp_status;            // 响应状态码
    HttpRecvStatus _recv_status; // 当前接收及解析的阶段状态
    HttpRequest _request;        // 已经解析得到的请求信息
private:
    bool ParseHttpLine(const std::string &line)
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase); // icase忽略大小写
        bool ret = std::regex_match(line, matches, e);

        if (ret == false)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400; // BAD REQUEST
            return false;
        }

        // 0 : GET /xxx/login?user=xiaoming&pass=123123 HTTP/1.1
        // 1 : GET
        // 2 : /xxx/login
        // 3 : user=xiaoming&pass=123123
        // 4 : HTTP/1.1
        // 请求方法的获取
        _request._method = matches[1];
        /*由于忽略了大小写，这里我们得到的方法可能是小写，所以需要转换成大写*/
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        // 资源路径的获取，需要进行URL解码操作，但是不需要+转空格
        _request._path = Util::UrlDecode(matches[2], false);
        // 协议版本获取
        _request._version = matches[4];

        // 参数的字符串的获取
        std::string query_string = Util::UrlDecode(matches[3], true);
        std::vector<std::string> query_arry;
        Util::Split(query_string, "&", &query_arry);
        for (auto &str : query_arry)
        {
            size_t pos = str.find("="); // user=xiaomin
            if (pos == std::string::npos)
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 400; // BAD REQUEST
                return false;
            }

            std::string key = Util::UrlDecode(str.substr(0, pos), true);
            std::string value = Util::UrlDecode(str.substr(pos + 1), true);
            _request.SetParam(key, value);
        }
        return true;
    }

    bool RecvHttpLine(Buffer *buf)
    {
        if (_recv_status != RECV_HTTP_LINE)
            return false;
        std::string line = buf->GetLineAndPop();

        if (line.size() == 0) // 1.读取到的数据没有一行
        {
            if (buf->ReadAbleSize() > MAX_LINE) // 缓冲区的数据大于 MAX_LINE
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 414; // URL TOO LONG
                return false;
            }

            // 缓冲区中数据不足一行，但是也不多，就等等新数据的到来
            return true;
        }
        if (line.size() > MAX_LINE) // 请求行的数据过大，存在异常
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 414; // URL TOO LONG

            return false;
        }

        bool ret = ParseHttpLine(line);
        if (ret == false)
        {
            Log::DEBUG("ParseHttpLine error");
            return false;
        }

        //Log::DEBUG("_recv_status 改变为RECV_HTTP_HEAD");
        // 处理完调整阶段状态
        _recv_status = RECV_HTTP_HEAD;
        return true;
    }

    // 头部处理
    bool ParseHttpHead(std::string &line)
    {
        // key: val\r\n
        if (line.back() == '\n')
            line.pop_back(); // 末尾是换行则去掉换行字符
        if (line.back() == '\r')
            line.pop_back(); // 末尾是回车则去掉回车字符

        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_status = RECV_HTTP_ERROR;
            _resp_status = 400; // BAD REQUEST
            return false;
        }

        std::string key = line.substr(0, pos);
        std::string value = line.substr(pos + 2);
        _request.SetHeader(key, value);
        //Log::DEBUG("key: %s, value:%s", key.c_str(), value.c_str());
        return true;
    }
    bool RecvHttpHead(Buffer *buf)
    {
        int a = 0;
        if (_recv_status != RECV_HTTP_HEAD)
        {
            Log::DEBUG("recv_status != RECV_HTTP_HEAD");
            return false;
        }
        while (1)
        {
            std::string line = buf->GetLineAndPop();
            //Log::DEBUG("头部的数据是: %s", line.c_str());
            if (line.size() == 0) // 1.读取到的数据没有一行
            {
                if (buf->ReadAbleSize() > MAX_LINE) // 缓冲区的数据大于 MAX_LINE
                {
                    _recv_status = RECV_HTTP_ERROR;
                    _resp_status = 414; // URL TOO LONG
                    return false;
                }

                // 缓冲区中数据不足一行，但是也不多，就等等新数据的到来
                return true;
            }

            if (line.size() > MAX_LINE) // 请求行的数据过大，存在异常
            {
                _recv_status = RECV_HTTP_ERROR;
                _resp_status = 414; // URL TOO LONG
                return false;
            }
            // 在头部处理中最后一个是\r\n 或者\n
            if (line == "\n" || line == "\r\n")
            {
                //Log::DEBUG("解析完毕");
                break;
            }

            bool ret = ParseHttpHead(line);
            if (ret == false)
            {
                return false;
            }
        }
        _recv_status = RECV_HTTP_BODY;

        return true;
    }

    bool RecvHttpBody(Buffer *buf)
    {
        if (_recv_status != RECV_HTTP_BODY)
            return false;
        // 1.获取正文长度
        size_t content_length = _request.ContentLength();
     //   std::cout << "获得的正文长度是： " << content_length << std::endl;
        if (content_length == 0)
        {
            // 没有正文，则请求接收解析完毕
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        // 2. 缓冲区中数据，包含了当前请求的所有正文，则取出所需的数据
        size_t real_len = content_length - _request._body.size();
        // 3.1判断当前缓冲区中的数据是否>= real_len
        if (buf->ReadAbleSize() >= real_len)
        {
            _request._body.append(buf->ReadPosition(), real_len);
            buf->MoveReadOffset(real_len);
            _recv_status = RECV_HTTP_OVER;
            return true;
        }

        // 3.2缓冲区中数据，无法满足当前正文的需要，数据不足，取出数据，然后等待新数据到来
        _request._body.append(buf->ReadPosition(), buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        // 这里不能改变状态，因为数据接收并没有完成
        return true;
    }

public:
    HttpContext() : _resp_status(200), _recv_status(RECV_HTTP_LINE) {}
    void ReSet()
    {
        _resp_status = 200;
        _recv_status = RECV_HTTP_LINE;
        _request.ReSet();
    }
    int GetRespStatus() { return _resp_status; }
    HttpRecvStatus GerRecvStatus() { return _recv_status; }
    HttpRequest &GetRequest() { return _request; }

    void ParseHttpRequest(Buffer *buf) // 接收并解析http请求
    {
        // 不同的状态，做不同的事情，但是这里不要break， 因为处理完请求行后，应该立即处理头部，而不是退出等新数据
        //_recv_status标志位可以控制处理Recvhttp的阶段！！！
        switch (_recv_status)
        {
        case RECV_HTTP_LINE:
            RecvHttpLine(buf);
        case RECV_HTTP_HEAD:
            //Log::DEBUG("开始解析头部");
            RecvHttpHead(buf);
        case RECV_HTTP_BODY:
            RecvHttpBody(buf);
        }
        return;
    }
};

class HttpServer
{
    using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;

private:
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir; // 静态资源根目录
    TcpServer _server;

private:
    // 错误页面设置
    void ErrorHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        //Log::DEBUG("错误页面");
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_status);
        body += " ";
        body += Util::StatusDesc(rsp->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据，当作响应正文，放入rsp中
        rsp->SetContent(body, "text/html");
    }
    // 将HttpResponse的要素按照http协议格式进行组织并且发送出去
    void WriteResponse(const PtrConnection &conn, const HttpRequest &req, HttpResponse &rsp)
    {
        // 完善头部
        if (req.Close() == true)
        {
            rsp.SetHeader("Connection", "close");
        }
        else
        {
            rsp.SetHeader("Connection", "keep-alive");
        }

        if (rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
        {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
        {
            rsp.SetHeader("Content-Type", "application/octet-stream"); // 默认二进制
        }
        if (rsp._redirect_flag == true)
        {
            rsp.SetHeader("Location", rsp._redirect_url);
        }

        // 按照http格式进行组织
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._status) << " " << Util::StatusDesc(rsp._status) << "\r\n";
        for (auto &head : rsp._headers)
        {
            rsp_str << head.first << ": " << head.second << "\r\n";
        }

        rsp_str << "\r\n";
        rsp_str << rsp._body;
        // 3.发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }

    // 静态资源的请求处理
    bool IsFileHandler(const HttpRequest &req)
    {
        // 静态根目录必须设置
        if (_basedir.empty() == true)
        {
            return false;
        }
        // 请求方法 必须是GER 或者 HEAD
        if (req._method != "GET" && req._method != "HEAD")
        {
            return false;
        }
        // 请求路径必须合法
        if (Util::ValidPath(req._path) == false)
        {
            return false;
        }
        // 请求资源必须存在，且是普通文件
        /*这里存在一个特殊情况， 当访问的是 "/" 的时候 我们要返回一个默认页面*/
        // 为了避免直接修改请求的资源路径，因此定义一个临时对象，如果是功能性请求我们修改路径会造成错误
        std::string req_path = _basedir + req._path;
        if (req_path.back() == '/')
        {
            req_path += "index.html";
        }

        if (Util::IsRegularFile(req_path) == false)
        {
            return false;
        }
        return true;
    }

    void FileHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
        {
            req_path += "index.html";
        }

        // 读取文件内容
        bool ret = Util::ReadFile(req_path, &rsp->_body);
        if (ret == false)
        {
            return;
        }
        // 设置Content-Type
        std::string mime = Util::GetMimeTypeFromExtension(req_path);
        rsp->SetHeader("Content-Type", mime);
    }
    // 功能性请求的分类处理
    void Dispatcher(HttpRequest &req, HttpResponse *rsp, Handlers &handlers)
    {
        // 在对应请求方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
        // 思想：路由表存储的时键值对 -- 正则表达式 & 处理函数
        // 使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        for (auto &handler : handlers)
        {
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;

            bool ret = std::regex_match(req._path, req._matches, re);
            if (ret == false)
            {
                continue;
            }

            functor(req, rsp); // 存在匹配的处理函数，则执行
            return;
        }
        // 没有匹配的函数
        rsp->_status = 404;
    }

    // 通过判断方法，来反馈一个对应的内容
    void Route(HttpRequest &req, HttpResponse *rsp)
    {
        // 加上重定向逻辑
        if (req._path == "/oldpage")
        {
            rsp->SetRedirect("/newpage"); // 默认302
            return;
        }

        if (req._path == "/newpage")
        {
            std::string body = "<html><body><h1>Welcome to the new page!</h1></body></html>";
            rsp->SetContent(body, "text/html");
            return;
        }
        // 判断是否是静态资源
        if (IsFileHandler(req) == true)
        {
            FileHandler(req, rsp);
            return;
        }

        if (req._method == "GET" || req._method == "HEAD")
        {
            return Dispatcher(req, rsp, _get_route);
        }
        else if (req._method == "POST")
        {
            return Dispatcher(req, rsp, _post_route);
        }
        else if (req._method == "PUT")
        {
            return Dispatcher(req, rsp, _put_route);
        }
        else if (req._method == "DELETE")
        {
            return Dispatcher(req, rsp, _delete_route);
        }
        rsp->_status = 405; // Method Not Allowed
        return;
    }
    // 设置上下文
    void OnConnected(const PtrConnection &conn)
    {
        conn->SetContext(HttpContext());
        Log::DEBUG("NEW CONNECTION %p", conn.get());
    }
    // 缓冲区数据解析+处理
    void OnMessage(const PtrConnection &conn, Buffer *buffer)
    {
        while (buffer->ReadAbleSize() > 0)
        {
            // 1. 获取上下文
            HttpContext& context = conn->GetContext()->GetContent<HttpContext>(); // 这里是引用
            // 2. 通过上下文对缓冲区数据进行解析，得到HttpRequest对象
            //   1. 如果缓冲区的数据解析出错，就直接回复出错响应
            //   2. 如果解析正常，且请求已经获取完毕，才开始去进行处理
            context.ParseHttpRequest(buffer);
            HttpRequest &req = context.GetRequest();
            HttpResponse rsp(context.GetRespStatus());
            if (context.GetRespStatus() >= 400)
            {
                // 进行错误响应，关闭连接
                ErrorHandler(req, &rsp);       // 填充一个错误显示页面数据到rsp的_body中
                WriteResponse(conn, req, rsp); // 将错误信息发送给用户
                context.ReSet();
                buffer->MoveReadOffset(buffer->ReadAbleSize()); // 清空缓冲区的数据
                conn->Shutdown();
                return;
            }

            if (context.GerRecvStatus() != RECV_HTTP_OVER)
            { // 当前请求还没有接收完整,则退出，等新数据到来再重新继续处理
                return;
            }
            // 3. 请求路由 + 业务处理,将处理后的数据放入到rsp._body中去
            /*简单的对重定向进行处理*/
            // auto Route = [&](HttpRequest &req, HttpResponse *rsp)
            // {
            //     // 示例：如果请求路径是 /oldpage → 重定向到 /newpage
            //     if (req._path == "/oldpage")
            //     {
            //         rsp->SetRedirect("/newpage"); // 默认 302 临时重定向
            //         return;
            //     }

            //     // 示例：如果请求路径是 /newpage → 返回一个页面
            //     if (req._path == "/newpage")
            //     {
            //         std::string body = "<html><body><h1>Welcome to the new page!</h1></body></html>";
            //         rsp->SetContent(body, "text/html");
            //         return;
            //     }

            //     // // 其他路径 → 返回 404
            //     // rsp->_status = 404;
            //     // std::string body = "<html><body><h1>404 Not Found</h1></body></html>";
            //     // rsp->SetContent(body, "text/html");
            // };

            Route(req, &rsp);
            // 4. 对HttpResponse进行组织发送
            WriteResponse(conn, req, rsp);
            // 5. 重置上下文
            context.ReSet();
            // 6. 根据长短连接判断是否关闭连接或者继续处理
            if (rsp.Close() == true)
                conn->Shutdown();
        }
    }

public:
    HttpServer(int port, int timeout = 10) : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageedCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    void SetBaseDir(const std::string &path) { _basedir = path; }

    // Get等函数的作用是加入到映射中：pattern实际上是正则表达式
    void Get(const std::string &pattern, const Handler &handler) { _get_route.push_back(std::make_pair(std::regex(pattern), handler)); }

    void Post(const std::string &pattern, const Handler &handler) { _post_route.push_back(std::make_pair(std::regex(pattern), handler)); }
    void Put(const std::string &pattern, const Handler &handler) { _put_route.push_back(std::make_pair(std::regex(pattern), handler)); }
    void Delete(const std::string &pattern, const Handler &handler) { _delete_route.push_back(std::make_pair(std::regex(pattern), handler)); }
    void SetThreadCount(int count) { _server.SetThreadCount(count); }
    void Start() { _server.Start(); }
};